<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Db;
//use addons\yunpian\Yunpian;
use think\Log;
use think\captcha\Captcha;
use think\Config;

/**
 * 手机短信接口
 */
class Sms extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send()
    {
        $company_serial = $this->request->request('cs');
        $mobile = $this->request->request('mobile');
        $event = $this->request->request('event');
        $event = $event ? $event : 'register';
        $device_plat = $this->request->request('device_plat');      //设备, 据此是否需要判断图片验证码
        $captcha = str_replace(' ', '', $this->request->request('captcha'));
        $data = ['type'=>'img_captcha'];
        $params = $this->request->param();
        if (isset($params['device_id'])){
            if ($params['device_brand'] == 'iPhone6s' || $params['device_id'] == "DACD4A5C-DE27-48C7-BBE2-EA64AF1A066E"){
                $this->error(__('单小时内发送已达5次，过于频繁'), $data);
            }
        }
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'), $data);
        }
        // 非手机端需要图片验证码，（如果pc端不要验证这里再设置个'pc'  '1', 'android', 'ios', 'pc'）
        if (!in_array($device_plat, ['1', 'android'])) {
            if (!$captcha) {
                $this->error(__('请输入图片验证码'), $data);
            }
            $newCaptcha = new Captcha();
            if(!$newCaptcha->check($captcha)) {
                $data['type'] = '';
                $this->error(__('图片验证码不正确'), $data);
            }
        }
        
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('60秒内不可重复发送'), $data);
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        $mobileSendTotal = \app\common\model\Sms::where(['mobile' => $mobile])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >=15) {
            $this->error(__('单小时内此IP发送已达15次，过于频繁'), $data);
        }
        if ($mobileSendTotal >=5) {
            $this->error(__('单小时内发送已达5次，过于频繁'), $data);
        }
        if ($event) {
            // $userinfo = User::getByMobile($mobile);
            $account_info = Db::name('account')->where(['username'=>$mobile])->field('id')->find();

//            if ($company_serial) {
//                $checkuc = $this->auth->checkUserCompany($account_info['id'], $company_serial);
//            }else{
               // $checkuc = $this->auth->checkUserCompany($account_info['id'], '');
           // }

           // if ($event == 'register' && $checkuc) {
            if ($event == 'register') {
                //已被注册
                //$msg = $company_serial ? '您已加入当前公司' : '手机号码已注册';
                //$data['go_login'] = 1;
                if($account_info){
                    $this->error('手机号码已注册');
                }
                //$this->error(__($msg), $data);
            } else if (in_array($event, ['changemobile'])) {
                //被占用
                $this->error(__('已被占用'), $data);
            } else if (in_array($event, ['changepwd', 'resetpwd']) && !$account_info) {
                //未注册
                $this->error(__('手机号码尚未注册'), $data);
            }

        }

        $default_sms = config('default_sms');

        switch ($event) {
            case 'login':
                // 登录验证模板
                $tpl_id = Config::get('captcha_tplcode.'.$default_sms)['login'];
                break;
            case 'resetpwd':
                // 找回密码模板
                $tpl_id = Config::get('captcha_tplcode.'.$default_sms)['resetpwd'];
                break;
            default:
                // 注册模板
                $tpl_id = Config::get('captcha_tplcode.'.$default_sms)['register'];
                break;
        }

        $code = mt_rand(1000, 9999);
        $time = time();
        $ip = request()->ip();
        $sms_save = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);

        $sign = config('captcha_tplcode.ali')['sign'];
        $templateParam = ['code' => $code];
        $ret = $this->aliSendSms($mobile, $sign, $tpl_id, $templateParam);
        if ($ret['code'] != 1) {
            $sms_save->delete();
            $this->error(__('发送失败，请重试').'('.$ret['msg'].')', $data);
        }else{
            if ($ipSendTotal >=10) {
                $total_msg = __('发送成功。单小时内此IP发送次数过多，还可以发送 %s 次', (15-$ipSendTotal));
            }elseif($mobileSendTotal >=3){
                $total_msg = __('发送成功。单小时内发送次数过多，还可以发送 %s 次', (5-$mobileSendTotal));
            }else{
                $total_msg = __('发送成功');
            }
            $this->success($total_msg, $data, 200);
        }

    }

    /**
     * 检测验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $captcha 验证码-短信
     */
    public function check()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->request("captcha");//短信验证码

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        $ret = Smslib::check($mobile, $captcha, $event);
        if ($ret) {//短信验证成功
            $this->success(__('成功'),null,200);

        } else {
            $this->error(__('验证码不正确'));
        }

    }

    public function getTemplate(){
        $tpl_id = $this->request->request("tpl_id");

        $ret = Smslib::getTemplate($tpl_id);
        if ($ret) {
            $this->success(__('获取成功'), $ret);
        } else {
            $this->error(__('获取失败'));
        }
    }

    // 云片添加模板回调
    public function ypCallbackTemplate(){
        $tpl_id = $this->request->request("tpl_id");
        $tpl_content = $this->request->request("tpl_content");
        $check_status = $this->request->request("check_status");
        $reason = $this->request->request("reason");
        if (!$tpl_id || !$check_status) {
            $this->error(__('缺少必要参数'));
        }

        $ret = Db::name('smstemplate')
            ->where(['templatenum'=>$tpl_id, 'platform'=>1])
            ->update(['check_status'=>$check_status, 'reason'=>$reason]);
        if ($ret) {
            $this->success(__('回调成功'));
        }else{
            $this->error(__('回调失败'));
        }
    }

    /**
     * 阿里短信单发
     * 调用形式：aliSendSms('手机号', '签名', '模板号', ['变量'=>'变量值'])
    */
    public function aliSendSms($mobile, $sign, $templateCode, $templateParam) {
        $config = get_addon_config('alisms');
        $sign = $sign ? $sign : config('showWords.project_name')['zh-cn'];
        if (!$mobile || !$sign || !$templateCode) {
            $this->error(__('手机号、短信签名和短信模板号均不可为空'));
        }
        $sign = $sign ? $sign : $config['sign'];
        $alisms = new \addons\alisms\library\Alisms();
        $ret = $alisms->mobile($mobile)
            ->sign($sign)    
            ->template($templateCode)
            ->param($templateParam)
            ->send();
        if ($ret) {
            return ['code'=>1, 'msg'=>'发送成功'];
        }else {
            return ['code'=>0, 'msg'=>$alisms->getError()];
        }
    }

    /* 
     * 阿里短信群发
     * 调用形式：aliSendBatch(['手机号'], ['签名'], '模板号', [['变量'=>'变量值']]);
    */
    public function aliSendBatch($mobileArr, $signList, $templateCode, $templateParam) {
        if (empty($mobileArr)) {
            $this->error(__('手机号码不可为空'));
        }
        if (empty($signList)) {
            $this->error(__('短信签名不可为空'));
        }
        if (!$templateCode) {
            $this->error(__('短信模板号不可为空'));
        }

        $alisms = new \addons\alisms\library\Alisms();
        $ret = $alisms->SendBatchSms($mobileArr, $signList, $templateCode, $templateParam);
        return $ret;
    }

}
